/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "XmlConfiguration.h"
#include <tinyxml.h>

namespace UGame {
namespace Util {

    void _BuildData(TiXmlNode* _Node, struct Configuration::Any& _Section)
    {
        for (TiXmlNode *_ChildNode = _Node->FirstChild(); _ChildNode; _ChildNode = _ChildNode->NextSibling())
        {
            switch (_ChildNode->Type())
            {
            case TiXmlNode::TINYXML_ELEMENT:
                TiXmlNode *_FirstChild = _ChildNode->FirstChild();
                TiXmlNode *_LastChild = _ChildNode->LastChild();
                if ((_FirstChild != NULL)
                    && (_FirstChild == _LastChild)
                    && (_FirstChild->ToText())) {
                    struct Configuration::Any _Any;
                    _Any.Key = _ChildNode->Value();
                    _Any.Value = _FirstChild->ToText()->Value();
                    _Section.Map[_Any.Key] = _Any;
                }
                else {
                    struct Configuration::Any _Any;
                    _Any.Key = _ChildNode->Value();
                    _BuildData(_ChildNode, _Any);
                    if (!(_Any.Value.empty() && _Any.Map.empty())) {
                        _Section.Map[_Any.Key] = _Any;
                    }
                }
                break;
            }
        }
    }

    XmlConfiguration::XmlConfiguration(void)
        : _root()
    {

    }

    XmlConfiguration::~XmlConfiguration(void)
    {

    }

    bool XmlConfiguration::Open(const std::string& _File)
    {
        TiXmlDocument _Doc;
        if (!_Doc.LoadFile(_File.c_str(), TIXML_DEFAULT_ENCODING)) {
            return false;
        }

        _root.Key = _Doc.RootElement()->Value();
        _BuildData(_Doc.RootElement(), _root);

        return true;
    }

	const struct Configuration::Any* XmlConfiguration::Get(const std::string& _Key) const
    {
        Configuration::ValueMap::const_iterator _Iter = _root.Map.find(_Key);
        if (_Iter != _root.Map.end()) {
            return &(_Iter->second);
        }
        return NULL;
    }
}}